package com.lechi.web.framework.websocket;

import com.alibaba.fastjson2.JSON;
import com.lechi.web.common.core.domain.AjaxResult;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@ServerEndpoint(value = "/websocket/{deviceId}")
@Component
public class WebSocketServer {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    @Getter
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    private static final ConcurrentHashMap<String, Set<Long>> sessionIdDeviceIdMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;


    /**
     * 自定义消息推送、可群发、单发
     *
     * @param message 消息
     */
    public static void sendInfo(Long deviceId, String message) {
//        log.error("【消息发送】，消息内容:{}", message);
        try {
            for (WebSocketServer item : webSocketSet) {
                if (sessionIdDeviceIdMap.get(item.session.getId()).contains(deviceId)) {
                    item.sendMessage(message);
                }
            }
        } catch (Exception e) {
            log.error("【消息发送】，消息内容:{}", message, e);
        }
    }

    /**
     * 连接建立成功调用的方法
     *
     * @param session 会话
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "deviceId") Long deviceId) {
        try {
            this.session = session;
            webSocketSet.add(this);
            if (sessionIdDeviceIdMap.get(session.getId()) == null) {
                Set<Long> set = new HashSet<>();
                set.add(deviceId);
                sessionIdDeviceIdMap.put(session.getId(), set);
            } else {
                Set<Long> set = sessionIdDeviceIdMap.get(session.getId());
                set.add(deviceId);
            }
            AjaxResult ajaxResult = AjaxResult.success();
            this.sendMessage(ajaxResult.toString());
        } catch (Exception e) {
            log.error("onOpen Exception", e);
        }
        log.debug("【新建连接】，连接总数:{}", webSocketSet.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            for (WebSocketServer item : webSocketSet) {
                item.sendMessage(JSON.toJSONString(message));
            }
        } catch (Exception e) {
            log.error("onMessage Exception", e);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        if (session != null) {
            try {
                session.close();
            } catch (IOException e) {
                log.error("onClose IOException", e);
            }
        }
        log.debug("【连接关闭】:{}", this);
    }

    /**
     * 发生错误时调用
     *
     * @param session 会话
     * @param error   错误信息
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("连接异常！", error);
    }

    /**
     * 发送信息
     *
     * @param message 消息
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}